import React, { useEffect, useMemo, useState } from 'react'
import { Button, Cascader, Col, message, Modal, Space, Spin, Table } from 'antd'
import http from '@/utils/request'
import Filter from '@/components/filter'
import OrderDetail from './orderDrawer/orderDetail'
import OrderAdd from './orderDrawer/orderAdd'
import DispatchOrder from '@/pages/order/dispatchOrder'
import IniviteOrder from './IniviteOrder/index'
import type { DictItem, optionConfigType, orderType } from '@/types'
import { getStatusDict } from '@/assets/dict'
import { filterOptions, orderListcolumns } from '@/pages/order/model'
import { useLocation } from 'react-router-dom'
import { authority } from '@/assets/dict/authCode'
import './index.scss'
import useChinaAreasStore from '@/store/chinaAreas'

interface filterType {
  pageSize?: number,
  pageNum?: number,
  current?: number,
  bizTeamName?: string,
  customerName?: string,
  comboName?: string,
  createUserName?: string,
  customerPhone?: string,
  status?: string,
  createEndTime?: string,
  createStartTime?: string,
  updateEndTime?: string,
  updateStartTime?: string,
  intendedDateEndTime?: string,
  intendedDateStartTime?: string,
  startAppointmentProcessingDate?: string,
  endAppointmentProcessingDate?: string,
  provinceCode?: number,
  cityCode?: number,
  areaCode?: number
}

const OrderList: React.FC = () => {
  const [dataSource, setDataSource] = useState<orderType[]>([])
  const [currentOrder, setCurrentOrder] = useState<orderType>()
  const [isDetailOpen, setIsDetailOpen] = useState(false)
  const [isAddOpen, setIsAddOpen] = useState(false)
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(false)
  const [statusDict, setStatusDict] = useState<DictItem[]>([])
  const [typeDict, setTypeDict] = useState<DictItem[]>([])
  const [teamType, setTeamType] = useState<'Biz' | 'Seats' | undefined>('Biz')
  const [pageConfig, setPageConfig] = useState<filterType>({
    pageSize: 10,
    pageNum: 1,
    current: 1,
    bizTeamName: '',
    customerName: '',
    comboName: '',
    createUserName: '',
    customerPhone: '',
    status: '',
    createEndTime: '',
    createStartTime: '',
    updateEndTime: '',
    updateStartTime: '',
    intendedDateEndTime: '',
    intendedDateStartTime: ''
  })

  const location = useLocation()

  const pathname = useMemo(() => {
    return location.pathname
  }, [location])

  const moduleName = useMemo(() => {
    return location.pathname.split('/')[2]
  }, [location])

  const showOrder = (row: orderType) => {
    setCurrentOrder(row)
    setIsDetailOpen(true)
  }
  const editOrder = (row: orderType) => {
    setCurrentOrder(row)
    setIsAddOpen(true)
  }

  const listUrlConfig: {[key: string]: { [key: string]: string }} = {
    // 全量订单
    'order-list': {
      list: '/disp/biz/order/page',
      export: '/disp/biz/order/export'
    },
    // 坐席订单
    'seat-order': {
      list: '/disp/biz/order/pageByCreateUserTeam',
      export: '/disp/biz/order/exportSeatTeamOrder'
    },
    // 邀约订单
    'invite-list': {
      list: '/disp/biz/order/pageInvitationOrder',
      export: '/disp/biz/order/exportInvitationOrder'
    },
    // 意向订单
    'intentional-order': {
      list: '/disp/biz/order/pageIntentionalOrder',
      export: '/disp/biz/order/exportIntentionalOrder'
    },
    // 回收订单
    'recycling-order': {
      list: '/disp/biz/order/pageRecyclingOrder',
      export: '/disp/biz/order/exportRecyclingOrder'
    },
    // 待确认订单
    'confirmation-order': {
      list: '/disp/biz/order/pagePendingConfirmationOrder',
      export: '/disp/biz/order/exportPendingConfirmationOrder'
    }
  }
  const queryOrderList = () => {
    setLoading(true)
    const url: string = listUrlConfig[moduleName].list
    http.post(url, {
      ...Object.fromEntries(Object.entries(pageConfig).filter(([_, val]) => val))
    }).then(res => {
      setTotal(res.data.total || 0)
      const ids: any[] = []
      setDataSource((res.data.list || []).filter((item: orderType) => {
        const result = !ids.includes(item.id)
        ids.push(item.id)
        return result
      }))
    }).finally(() => {
      setLoading(false)
    })
  }
  const [optionConfig, setOptionConfig] = useState<optionConfigType>({
    teams: [],
    bizTypes: [],
    comboIds: [],
    gifts: []
  })

  const setOptionByKey = (key: string, val: DictItem[]) => {
    setOptionConfig((optionConfig) => ({
      ...optionConfig,
      [key]: val
    }))
  }

  const operateDataList = () => {
    return [
      {
        label: '团队',
        labelKey: 'teamName',
        url: '/disp/biz/team/page',
        dictName: 'teams'
      },
      {
        label: '业务类型',
        labelKey: 'name',
        url: '/disp/biz/operation/pageBizType',
        dictName: 'bizTypes'
      },
      {
        label: '套餐',
        labelKey: 'name',
        url: '/disp/biz/operation/pageCombo',
        dictName: 'comboIds'
      },
      {
        label: '礼品',
        labelKey: 'name',
        url: '/disp/biz/operation/pageGift',
        dictName: 'gifts'
      }
    ].map(requestItem => {
      return http.post(requestItem.url, {
        pageNum: 1,
        pageSize: 99999
      }).then(res => {
        const options = (res?.data?.list || []).map((item: Record<string, string> & { id: string }) => {
          return {
            value: item.id,
            label: item[requestItem.labelKey],
            disabled: item.status !== 'Enable',
            teamType: item.teamType || ''
          }
        })
        setOptionByKey(requestItem.dictName, options)
      })
    })
  }

  const initPage = async () => {
    setLoading(true)
    operateDataList()
    try {
      const listStatus = await getStatusDict('/disp/biz/order/listOrderStatus')
      setStatusDict(listStatus)
      const listType = await getStatusDict('/disp/biz/order/listOrderType')
      setTypeDict(listType)
      setLoading(false)
      queryOrderList()
    } catch (e) {
      console.log(e)
      setLoading(false)
    }
  }

  useEffect(() => {
    initPage()
  }, [location])

  const pageChange = (pageNum: number, pageSize: number) => {
    pageConfig.pageSize = pageSize
    pageConfig.pageNum = pageNum
    pageConfig.current = pageNum
    queryOrderList()
  }

  const addressChange = (value: number[]) => {
    setPageConfig({
      ...pageConfig,
      provinceCode: value[0],
      cityCode: value[1],
      areaCode: value[2]
    })
  }

  const filterChange = (val: any, key: string) => {
    let { createEndTime,
      createStartTime,
      updateEndTime,
      updateStartTime,
      intendedDateStartTime,
      intendedDateEndTime,
      startAppointmentProcessingDate,
      endAppointmentProcessingDate
    } = pageConfig
    if (key === 'createTime') {
      createStartTime = val ? val[0].format('YYYY-MM-DD HH:mm:ss') : ''
      createEndTime = val ? val[1].endOf('day').format('YYYY-MM-DD HH:mm:ss') : ''
      setPageConfig((config) => ({
        ...config,
        pageNum: 1,
        current: 1,
        createStartTime,
        createEndTime
      }))
    } else if (key === 'updateTime') {
      updateStartTime = val ? val[0].format('YYYY-MM-DD HH:mm:ss') : ''
      updateEndTime = val ? val[1].endOf('day').format('YYYY-MM-DD HH:mm:ss') : ''
      setPageConfig((config) => ({
        ...config,
        pageNum: 1,
        current: 1,
        updateStartTime,
        updateEndTime
      }))
    } else if (key === 'intendedDate') {
      intendedDateStartTime = val ? val[0].format('YYYY-MM-DD HH:mm:ss') : ''
      intendedDateEndTime = val ? val[1].endOf('day').format('YYYY-MM-DD HH:mm:ss') : ''
      setPageConfig((config) => ({
        ...config,
        pageNum: 1,
        current: 1,
        intendedDateStartTime,
        intendedDateEndTime
      }))
    } else if (key === 'appointmentProcessingDate') {
      startAppointmentProcessingDate = val ? val[0].format('YYYY-MM-DD HH:mm:ss') : ''
      endAppointmentProcessingDate = val ? val[1].endOf('day').format('YYYY-MM-DD HH:mm:ss') : ''
      setPageConfig((config) => ({
        ...config,
        pageNum: 1,
        current: 1,
        startAppointmentProcessingDate,
        endAppointmentProcessingDate
      }))
    } else {
      setPageConfig((config) => ({
        ...config,
        pageNum: 1,
        current: 1,
        createEndTime,
        createStartTime,
        [key]: val
      }))
    }
  }

  const handleDetailClose = () => {
    setIsDetailOpen(false)
  }

  const handleAddClose = (refresh?: boolean) => {
    if (refresh) {
      queryOrderList()
    }
    setIsAddOpen(false)
  }

  const addOrder = () => {
    setCurrentOrder(undefined)
    setIsAddOpen(true)
  }

  const [dispatchVisible, setDispatchVisible] = useState<boolean>(false)
  const [inviteVisible, setInviteVisible] = useState<boolean>(false)
  const [inviteType, setInviteType] = useState<'Fail' | 'Batch-invite' | undefined>()

  const dispatchOrder = (row: React.SetStateAction<orderType | undefined>, type?: 'Biz' | 'Seats') => {
    setCurrentOrder(row)
    setDispatchVisible(true)
    setTeamType(type)
  }

  const handleSuccess = () => {
    setDispatchVisible(false)
    queryOrderList()
  }

  const iniviteOrder = (row: React.SetStateAction<orderType | undefined>, type?: 'Fail' | 'Batch-invite') => {
    setCurrentOrder(row)
    setInviteType(type)
    setInviteVisible(true)
  }

  const handleInviteSuccess = () => {
    setInviteVisible(false)
    setInviteType(undefined)
    queryOrderList()
  }

  const deleteOrder = (row: orderType) => {
    Modal.confirm({
      title: '确认删除',
      content: '确定要删除该订单吗？',
      okText: '确定',
      cancelText: '取消',
      onOk: async () => {
        try {
          await http.get('/disp/biz/order/delete', {
            params: {
              id: row.id
            }
          })
          message.success('删除成功')
          queryOrderList()
        } catch (error) {
          console.error('删除失败:', error)
        }
      }
    })
  }

  const exportList = () => {
    const { pageNum: _pageNum, pageSize: _pageSize, ...other } = pageConfig
    setLoading(true)
    http.post(listUrlConfig[moduleName].export, other, {
      responseType: 'blob',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      }
    }).then(res => {
      // 兼容不同后端返回的content-disposition格式
      let fileName = '订单列表.xlsx'
      const disposition = res.headers['content-disposition'] || res.headers['Content-Disposition']
      if (disposition) {
        const match = disposition.match(/filename[^;=\n]*=((['\"]).*?\2|[^;\n]*)/)
        if (match && match[1]) {
          fileName = decodeURIComponent(match[1].replace(/['"]/g, ''))
        }
      }
      const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
      const link = document.createElement('a')
      link.download = fileName
      link.style.display = 'none'
      link.href = URL.createObjectURL(blob)
      document.body.appendChild(link)
      link.click()
      URL.revokeObjectURL(link.href)
      document.body.removeChild(link)
    }).catch(err => {
      console.error('导出失败:', err)
      message.error('导出失败')
    }).finally(() => {
      setLoading(false)
    })
  }

  const handleBatchDispatchBiz = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择需要指派的订单')
      return
    }
    setDispatchVisible(true)
    dispatchOrder({ id: selectedRowKeys.join(',') } as unknown as orderType, 'Biz')
  }

  const handleBatchInvite = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请先选择需要邀约的订单')
      return
    }
    iniviteOrder({ id: selectedRowKeys.join(',') } as unknown as orderType, 'Batch-invite')
  }

  const rowSelection = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys: React.Key[]) => {
      setSelectedRowKeys(newSelectedRowKeys)
    }
  }
  const { chinaAreas } = useChinaAreasStore()
  const filter = (inputValue: string, path: any[]) =>
    path.some(
      (option) => (option.name as string).toLowerCase().indexOf(inputValue.toLowerCase()) > -1
    )

  return (
    <Spin spinning={loading}>
      <Filter
        prefix={(<Col className="filter-item" xs={24} md={12} lg={8} xl={6}>
          <div className="label">区域：</div>
          <Cascader
            options={chinaAreas}
            onChange={addressChange}
            fieldNames={{
              label: 'name',
              value: 'region',
              children: 'childRegion'
            }}
            placeholder="请选择省市区"
            changeOnSelect
            showSearch={{ filter }}
            style={{ width: '100%' }}
          />
        </Col>)}
        items={filterOptions(statusDict, pathname)}
        onChange={filterChange}
        onSure={queryOrderList}
        otherBtn={
          authority(`${moduleName}-export`, <Button className="btn" onClick={exportList}>导出</Button>, pathname)
        } />
      <div className="gap10 flex-row" style={{ width: '100%' }}>
        <div className="flex1"/>
        {authority(`${moduleName}-add`, <Button onClick={addOrder}>添加</Button>)}
        {authority(`${moduleName}-dispatch-batch-biz`, <Button onClick={handleBatchDispatchBiz}>批量指派</Button>)}
        {authority(`${moduleName}-dispatch-batch`, <Button onClick={handleBatchInvite}>批量邀约</Button>)}
      </div>
      <Table
        rowSelection={rowSelection}
        pagination={{ 
          position: ['bottomRight'], 
          ...pageConfig, 
          total, 
          onChange: pageChange,
          showTotal: (total) => `共 ${total} 条`,
          pageSizeOptions: ['10', '20', '30', '50'],
          showSizeChanger: true
        }}
        dataSource={dataSource}
        scroll={{ x: 'max-content' }}
        columns={[
          ...orderListcolumns(pathname),
          {
            title: '操作',
            key: 'action',
            fixed: 'right',
            render: (_: any, row: any) => (
              <Space className="btn-container" size="middle">
                <a onClick={() => showOrder(row)} role="button">详情</a>
                {authority(`${moduleName}-dispatch`, <a role="button" onClick={() => dispatchOrder(row, 'Biz')}>指派</a>)}
                {authority(`${moduleName}-dispatch-set`, <a role="button" onClick={() => dispatchOrder(row, 'Seats')}>坐席转派</a>)}
                {authority(`${moduleName}-dispatch-invite`, <a role="button" onClick={() => iniviteOrder(row)}>邀约</a>)}
                {authority(`${moduleName}-dispatch-invite-fail`, <a role="button" onClick={() => iniviteOrder(row, 'Fail')}>邀约失败</a>)}

                {!['Success'].includes(row.status) && authority(`${moduleName}-edit`) ?
                  <a role="button" onClick={() => editOrder(row)}>编辑</a> :
                  null
                }
                {moduleName === 'intentional-order' && authority(`${moduleName}-delete`) ?
                  <a role="button" onClick={() => deleteOrder(row)}>删除</a> :
                  null
                }
              </Space>
            )
          }
        ]}
        rowKey="id" />
      <OrderDetail isOpen={isDetailOpen} order={currentOrder} onClose={handleDetailClose} />
      <OrderAdd
        isOpen={isAddOpen}
        order={currentOrder}
        typeDict={typeDict}
        optionConfig={optionConfig}
        onClose={handleAddClose} />
      <DispatchOrder
        teamType={teamType}
        order={currentOrder}
        isOpen={dispatchVisible}
        teamList={optionConfig.teams || []}
        success={handleSuccess}
        close={() => setDispatchVisible(false)} />
      {/* <IniviteOrder */}
      {/*   isOpen={isBatchInviteOpen} */}
      {/*   order={{ id: selectedRowKeys.join(',') } as unknown as orderType} */}
      {/*   success={handleBatchInviteSuccess} */}
      {/*   close={() => setIsBatchInviteOpen(false)} */}
      {/*   isBatch={true} */}
      {/* /> */}
      <IniviteOrder
        order={currentOrder}
        isOpen={inviteVisible}
        type={inviteType}
        success={handleInviteSuccess}
        close={() => {
          setInviteVisible(false)
          setInviteType(undefined)
        }}
      />
    </Spin>
  )
}
export default OrderList